#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE 64

// argc是命令行参数的个数
int main(int argc, char *argv[])
{
    // for(int idx = 0;idx < argc;idx++)
    // {
    //     printf("argv[%d] = %s\n",idx,argv[idx]);
    // }

    if (argc != 3)
    {
        printf("param num is invaild.");
        exit(-1);
    }

    const char *srcFile = argv[1];

    int dstMode = 0;
    // 判断原文件是否具备写权限
    int ret = access(srcFile,R_OK);
    if(ret == 0)
    {
        printf("srcFile read permission");
        dstMode |= R_OK;
    }
    // printf("%d\n",ret);
    // 判断原文件是否具备读权限
    ret = access(srcFile,W_OK);
    if(ret == 0)
    {
        printf("srcFile write permission");
        dstMode |= W_OK;
    }
    //  执行权限
    ret = access(srcFile,X_OK);
    if(ret == 0)
    {
        printf("srcFile execute permission");
        dstMode |= X_OK;
    }

    const char *dstFile = argv[2];

    // 用access函数判断文件是否存在
    ret = access(srcFile,F_OK);
    if(ret == -1)
    {
        printf("src file open error:\n");
        exit(-1);
    }

    int srcFd = open(srcFile, O_RDONLY);
    if (srcFd == -1)
    {
        printf("src file open error:\n");
        exit(-1);
    }

    
    // 程序走到这，说明原文件是存在的
    int dstFd = open(dstFile, O_WRONLY | O_CREAT, dstMode);
    if (dstFd == -1)
    {
        printf("dst file open error:\n");
        exit(-1);
    }

    char buffer[BUFFER_SIZE] = {0};
    int readBytes = 0;
    while (1)
    {
        // 读到的字节数
        readBytes = read(srcFd, buffer, BUFFER_SIZE - 1);
        if (readBytes < BUFFER_SIZE - 1 || (readBytes <= 0))
        {
            write(dstFd, buffer, readBytes);
            break;
        }
        write(dstFd, buffer, readBytes);

        memset(buffer, 0, sizeof(buffer));
    }

    // 关闭文件
    close(srcFd);
    close(dstFd);

    return 0;
}
